Iterators and Generators Homework

Problem 1

Create a generator that generates the squares of numbers up to some number N.


In [4]:
def gensquares(N):
    for num in xrange(1,N):
        yield num**2

In [5]:
for x in gensquares(10):
    print x


1
4
9
16
25
36
49
64
81

Problem 2

Create a generator that yields "n" random numbers between a low and high number (that are inputs). Note: Use the random library. For example:


In [6]:
import random

random.randint(1,10)


Out[6]:
1

In [7]:
def rand_num(low,high,n):
    for num in xrange(n):
        yield random.randint(low,high)

In [8]:
for num in rand_num(1,10,12):
    print num


7
6
8
1
10
2
5
9
5
7
7
3

Problem 3

Use the iter() function to convert the string below


In [12]:
s = 'hello'
s_iter = iter(s)

next(s_iter)
next(s_iter)

#code here


Out[12]:
'e'

Problem 4

Explain a use case for a generator using a yield statement where you would not want to use a normal function with a return statement.

loop over a large matrix or data frame

Extra Credit!

Can you explain what gencomp is in the code below? (Note: We never covered this in lecture! You will have to do some googling/Stack Overflowing!)


In [13]:
my_list = [1,2,3,4,5]

gencomp = (item for item in my_list if item > 3)

for item in gencomp:
    print item


4
5

Hint google: generator comprehension is!

Great Job!


In [ ]: